<template>
	<view class="topic-container">
		<!-- 导航栏 -->
		<uv-navbar title="" :border="false" :autoBack="true" :placeholder="true" leftIcon="arrow-left"
			:titleStyle="{ color: '#333' }">
			<template #center>
				<view class="nav-title">答题</view>
			</template>
			<template #right>
				<view class="answer-card" @click="showAnswerCard">
					<text>答题卡</text>
				</view>
			</template>
		</uv-navbar>

		<!-- 题目进度 -->
		<view class="progress-bar">
			<text>{{ currentIndex + 1 }}/{{ totalQuestions }}</text>
			<view class="progress-line">
				<view class="progress-active" :style="{ width: progressWidth }"></view>
			</view>
		</view>

		<!-- 题目内容 -->
		<view class="question-container">
			<!-- 题目类型 -->
			<view class="question-type">{{ questionTypeText }}</view>

			<!-- 题目 -->
			<view class="question-title">
				<text class="question-number">{{ currentIndex + 1 }}. </text>
				<text class="question-score" v-if="currentQuestion.score">({{ currentQuestion.score }}分) </text>

				<PraseContent v-if="currentQuestion.title" :contents="currentQuestion.title" />
			</view>

			<!-- 根据题型渲染不同组件 -->
			<!-- {{ currentQuestion.options  -->
			<SingleChoice v-if="currentQuestion.questionType === 'single_choice'" :options="uniqueOptions"
				:userAnswer.sync="userAnswer" :answer="currentQuestion.answer" :showAnswer="showAnswer"
				@select="handleAnswerSelect" />

			<MultipleChoice v-else-if="currentQuestion.questionType === 'multiple_choice'" :options="uniqueOptions"
				:userAnswer.sync="userAnswer" :answer="currentQuestion.answer" :showAnswer="showAnswer"
				@select="handleAnswerSelect" />

			<TrueFalse v-else-if="currentQuestion.questionType === 'true_false'" :userAnswer.sync="userAnswer"
				:answer="currentQuestion.answer" :showAnswer="showAnswer" @select="handleAnswerSelect" />

			<FillBlank v-else-if="currentQuestion.questionType === 'fill_blank'" :userAnswer.sync="userAnswer"
				:answer="currentQuestion.answer" :showAnswer="showAnswer" @select="handleAnswerSelect" />

			<!-- 答案解析 -->
			<view v-if="showAnswer" class="answer-analysis">
				<view class="answer-result">
					<text>正确答案: {{ currentQuestion.answer }}，</text>
					<text>我的答案: {{ userAnswer }}</text>
				</view>
				<view class="analysis-content">
					<text>答案解析：</text>
					<text>{{ currentQuestion.explanation }}</text>
				</view>
			</view>
		</view>

		<!-- 底部导航 -->
		<view class="bottom-nav">
			<view class="nav-btn prev-btn" v-if="currentIndex > 0" @click="prevQuestion">上一题</view>

			<view class="nav-btn next-btn" @click="nextQuestion">
				{{ totalQuestions - 1 == currentIndex ? '提交' : '下一题' }}
			</view>
		</view>

		<!-- 答题卡组件 -->
		<AnswerCard ref="answerCard" :questions="questions" :currentIndex="currentIndex" @select="selectQuestion" />
	</view>
</template>

<script>
import AnswerCard from '@/components/topic/AnswerCard.vue';
import SingleChoice from '@/components/topic/SingleChoice.vue';
import MultipleChoice from '@/components/topic/MultipleChoice.vue';
import TrueFalse from '@/components/topic/TrueFalse.vue';
import FillBlank from '@/components/topic/FillBlank.vue';
import PraseContent from '@/components/topic/PraseContent.vue';
import { mapGetters } from 'vuex'
import { isAnswerCorrect } from '@/utils/answerValidator';

export default {
	components: {
		AnswerCard,
		SingleChoice,
		MultipleChoice,
		TrueFalse,
		FillBlank,
		PraseContent
	},
	data() {
		return {
			currentIndex: 0,
			userAnswer: '',
			showAnswer: false,
			updateTimeInterval: null,
			questions: [
				// {
				// 	id: 1,
				// 	title: '在计算机系统的多层次结构中，处于硬联逻辑与传统机器（机器指令语言）之间的是（   ）',
				// 	score: 5.0,
				// 	type: 'single',
				// 	options: [
				// 		{ label: 'A', optionContent: '操作系统机器' },
				// 		{ label: 'B', optionContent: '微程序机器' },
				// 		{ label: 'C', optionContent: '汇编语言机器' },
				// 		{ label: 'D', optionContent: '高级语言机器' }
				// 	],
				// 	answer: 'B',
				// 	userAnswer: '',
				// 	explanation: '计算机系统的多层次结构从底层到高层依次是：硬联逻辑层、微程序机器层、传统机器层、操作系统层、汇编语言层、高级语言层。'
				// },
			]
		}
	},
	computed: {
		uniqueOptions() {
			const uniqueMap = new Map();
			this.currentQuestion.options.forEach(option => {
				if (!uniqueMap.has(option.label))
					uniqueMap.set(option.label, option);
			});
			return Array.from(uniqueMap.values());
		},
		totalQuestions() {
			return this.questions.length;
		},
		currentQuestion() {
			return this.questions[this.currentIndex] || {};
		},
		progressWidth() {
			const progress = ((this.currentIndex + 1) / this.totalQuestions) * 100;
			return `${progress}%`;
		},
		questionTypeText() {
			const typeMap = {
				'single_choice': '单选题',
				'multiple_choice': '多选题',
				'true_false': '判断题',
				'fill_blank': '填空题'
			};
			return typeMap[this.currentQuestion.questionType] || '单选题';
		},
		// 判断题目标题是否为JSON格式
		isJsonTitle() {
			if (!this.currentQuestion.title) return false;
			try {
				// 尝试解析JSON
				const parsed = JSON.parse(this.currentQuestion.title);
				return Array.isArray(parsed) && parsed.length > 0;
			} catch (e) {
				return false;
			}
		},
		// 解析JSON格式的题目标题
		parsedTitle() {
			if (!this.isJsonTitle) return [];
			try {
				return JSON.parse(this.currentQuestion.title);
			} catch (e) {
				return [];
			}
		},
		...mapGetters(['userExams']),
	},
	onLoad() {
		this.getQuestionsList()
		if (!this.userExams.userExamId) {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}
		this.initUpdateTime()
	},
	beforeDestroy() {
		if (this.updateTimeInterval) {
			clearInterval(this.updateTimeInterval)
			this.updateTimeInterval = null
		}
	},
	methods: {
		// 获取图片URL
		getImageUrl(imageId) {
			// 根据实际情况返回图片URL，这里假设imageId是图片的唯一标识
			// 使用项目配置中的baseUrl，去掉端口号
			const baseUrlWithoutPort = this.$config.baseUrl.replace(/:\d+/, '');
			return baseUrlWithoutPort + '/image/' + imageId;
		},
		// 预览图片
		previewImage(imageId) {
			const imageUrl = this.getImageUrl(imageId);
			// 获取所有图片URL用于预览
			let imageUrls = [];
			if (this.isJsonTitle && this.parsedTitle) {
				imageUrls = this.parsedTitle
					.filter(item => item.type === 'image')
					.map(item => this.getImageUrl(item.content));
			} else {
				imageUrls = [imageUrl];
			}
			// 使用uni-app的预览图片API
			uni.previewImage({
				urls: imageUrls,
				current: imageUrl
			});
		},
		initUpdateTime() {

			if (this.updateTimeInterval) {
				clearInterval(this.updateTimeInterval)
				this.updateTimeInterval = null
			}

			this.updateTimeInterval = setInterval(() => {
				if (this.questions[this.currentIndex] &&
					this.questions[this.currentIndex].userAnswer &&
					this.questions[this.currentIndex].userAnswer.stayTime) {
					this.questions[this.currentIndex].userAnswer.stayTime++
				} else if (this.questions[this.currentIndex]) {
					if (!this.questions[this.currentIndex].userAnswer) {
						this.questions[this.currentIndex].userAnswer = {
							stayTime: 1,
						};
					} else {
						this.questions[this.currentIndex].userAnswer.stayTime = 1;
					}
				}
			}, 1000)
		},
		getQuestionsList() {
			this.$api('getQuestionsList', {
				examId: this.userExams.examId,
			})
				.then(res => {
					if (res.code == 200) {
						this.questions = res.data.questions;
					}
				})
		},
		// 用户选择
		handleAnswerSelect(value) {
			if (this.showAnswer) return;
			this.userAnswer = value;

			// 更新当前题目的用户答案
			let question = this.questions[this.currentIndex]

			if (question.userAnswer) {
				question.userAnswer.answerContent = value
				question.isCorrect = isAnswerCorrect(question) ? 1 : 0
			} else {
				question.userAnswer = {
					answerContent: value,
					stayTime: 0,
				};
				question.isCorrect = isAnswerCorrect(question) ? 1 : 0
			}

			this.$api('userExamsSelectAnswer', {
				recordId: question.userAnswer.recordId || null,
				answerTime: this.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
				questionType: question.questionType,
				questionId: question.questionId,
				userExamId: this.userExams.userExamId,
				stayTime: question.userAnswer.stayTime || 0,
				answerContent: question.userAnswer.answerContent,
				isCorrect: question.isCorrect || 0,
				scoreEarned: question.isCorrect ? question.score : 0,
			})
            .then(res => {
                if (res.code == 200) {
                    question.userAnswer.recordId = res.data.recordId
                }
            })
            .catch(error => {
                console.error('保存答案失败:', error);
            })

			// 不显示答案
			// this.showAnswer = true;
		},
		nextQuestion() {
			if (this.currentIndex < this.totalQuestions - 1) {
				this.currentIndex++;
				this.resetQuestion();
			} else {
				this.$api('userExamsSubmit', {
					userExamId: this.userExams.userExamId,
					examId: this.userExams.examId,
					// questions : this.questions,
					userAnswersList: this.questions.map(item => item.userAnswer)
				})
					.then(res => {
						if (res.code == 200) {
							uni.navigateTo({
								url: '/pages_order/result/result?id=' + res.data.userExamId
							})
						}
					})
			}
		},
		prevQuestion() {
			if (this.currentIndex > 0) {
				this.currentIndex--;
				this.resetQuestion();
			}
		},
		resetQuestion() {

			if (this.questions[this.currentIndex] && this.questions[this.currentIndex].userAnswer) {
				this.userAnswer = this.questions[this.currentIndex].userAnswer.answerContent || '';
			} else {
				this.userAnswer = '';
			}

			this.showAnswer = false;
		},
		showAnswerCard() {
			// 显示答题卡
			this.$refs.answerCard.open();
		},
		// 从答题卡选择题目
		selectQuestion(index) {
			this.currentIndex = index;
			this.resetQuestion();
		},
	}
}
</script>

<style lang="scss" scoped>
.topic-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding-bottom: 120rpx;
}

.title-item {
	display: inline-block;
	margin-right: 10rpx;
	flex-wrap: wrap;
	position: relative;
}

.question-title {
	/* 原有样式保持不变 */
	font-size: 32rpx;
	color: #333;
	line-height: 1.5;
	margin-bottom: 40rpx;
}

/* 添加图片容器样式，支持多图显示 */


/* 添加图片点击提示 */
.title-image {
	position: relative;
}

.title-image::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.3);
	opacity: 0;
	transition: opacity 0.3s;
	border-radius: 8rpx;
	z-index: 1;
}

.title-image::after {
	content: '点击查看';
	position: absolute;
	bottom: 10rpx;
	left: 0;
	right: 0;
	color: #fff;
	font-size: 20rpx;
	padding: 4rpx 0;
	text-align: center;
	opacity: 0;
	transition: opacity 0.3s;
	z-index: 2;
}

.title-image:active::before,
.title-image:active::after {
	opacity: 1;
}

.title-image {
	max-width: 240rpx;
	height: 180rpx;
	margin: 10rpx 10rpx 10rpx 0;
	border-radius: 8rpx;
	border: 1px solid #eee;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
	cursor: pointer;
	transition: all 0.3s;
	position: relative;
	display: inline-block;
}

.title-image:active {
	opacity: 0.8;
	transform: scale(0.98);
}

.nav-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.answer-card {
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
}

.progress-bar {
	padding: 20rpx 30rpx;
	display: flex;
	flex-direction: column;
	align-items: center;

	text {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.progress-line {
		width: 100%;
		height: 6rpx;
		background-color: #eee;
		border-radius: 6rpx;
		overflow: hidden;

		.progress-active {
			height: 100%;
			background-color: #007aff;
			transition: width 0.3s;
		}
	}
}

.question-container {
	background-color: #fff;
	margin: 20rpx 30rpx;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.question-type {
	font-size: 30rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 20rpx;
}

.question-title {
	font-size: 32rpx;
	color: #333;
	line-height: 1.5;
	margin-bottom: 40rpx;

	.question-number {
		font-weight: 500;
	}

	.question-score {
		color: #666;
	}
}

.options-container {
	margin-top: 30rpx;
}

.option-item {
	display: flex;
	align-items: flex-start;
	padding: 24rpx 20rpx;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
	background-color: #f8f8f8;
	border: 2rpx solid transparent;
	transition: all 0.3s;

	&.option-selected {
		background-color: #e6f2ff;
		border-color: #007aff;
	}

	&.option-correct {
		background-color: #e8f5e9;
		border-color: #4caf50;
	}

	&.option-wrong {
		background-color: #ffebee;
		border-color: #f44336;
	}

	.option-icon {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 20rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #666;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);

		.icon-correct {
			color: #4caf50;
		}

		.icon-wrong {
			color: #f44336;
		}
	}

	.option-text {
		flex: 1;
		font-size: 30rpx;
		color: #333;
		line-height: 1.5;
		padding-top: 6rpx;
	}
}

.answer-analysis {
	margin-top: 40rpx;
	padding: 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;

	.answer-result {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
	}

	.analysis-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
	}
}

.bottom-nav {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	height: 100rpx;
	background-color: #fff;
	border-top: 2rpx solid #eee;

	.nav-btn {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		color: #333;
	}

	.prev-btn {
		background-color: #f5f5f5;
		color: #666;
	}

	.next-btn {
		background-color: #007aff;
		color: #fff;
	}
}
</style>